package com.jack.lib.core.utils;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Handler;
import android.os.Message;


import com.blankj.utilcode.util.NetworkUtils;
import com.blankj.utilcode.util.ToastUtils;

import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.UnknownHostException;

/**
 * Created by chong on 2017/11/5.
 */

public class DownloadUtils {


    public interface OnDownloadListener{
        void onFinish();
        void onError(Exception e);
        void onProgress(float progress);
    }

    public static void download(Context context, final String path, final String filePath, final OnDownloadListener onDownloadListener) {


        if (!NetworkUtils.isAvailable()) {
            ToastUtils.showShort("网络不可用");
        }


        @SuppressLint("HandlerLeak") final Handler handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case 1:
                        onDownloadListener.onFinish();
                        break;
                    case 2:
                        if (((Exception) msg.obj).getClass() == UnknownHostException.class){
                            ToastUtils.showShort("路径有误");
                        }
                        onDownloadListener.onError(((Exception) msg.obj));
                        break;
                    case 3:
                        onDownloadListener.onProgress((Float) msg.obj);
                        break;
                }
            }
        };


        new Thread(() -> {
            try {

                URL url = new URL(path);
                HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                httpURLConnection.setReadTimeout(5000);
                httpURLConnection.setConnectTimeout(10000);


                InputStream inputStream = httpURLConnection.getInputStream();

                int contentLength = httpURLConnection.getContentLength();

                DataInputStream dis = new DataInputStream(httpURLConnection.getInputStream());
                FileOutputStream fos = new FileOutputStream(checkDirectory(filePath));

                byte[] buf = new byte[10240];
                int progress = 0;
                for (int readSize; (readSize = dis.read(buf)) > 0; ) {
                    fos.write(buf, 0, readSize);
                    progress += readSize;
                    Message message = handler.obtainMessage();
                    message.obj = progress * 1.0f / contentLength;
                    message.what = 3;
                    handler.sendMessage(message);
                }

                fos.flush();
                fos.close();
                dis.close();
                inputStream.close();

                handler.sendEmptyMessage(1);
                httpURLConnection.disconnect();

            } catch (Exception e) {
                Message message = handler.obtainMessage();
                message.obj = e;
                message.what = 2;
                handler.sendMessage(message);
                e.printStackTrace();
            }
        }).start();
    }

    private static File checkDirectory(String filePath) throws IOException {
        File baseFile = new File(filePath.substring(0, filePath.lastIndexOf("/")));
        if (!baseFile.exists()){
            baseFile.mkdirs();
        }
        File file = new File(filePath);
        file.createNewFile();
        return file;
    }


    public static String getInputStreamString(InputStream inputStream) throws IOException {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        int len;
        while ((len = inputStream.read()) != -1){
            byteArrayOutputStream.write(len);
        }
        return byteArrayOutputStream.toString();
    }
}
